import {defineStore} from 'pinia'
import {authApi} from '@/api'
import type {UserLoginDTO, UserRegisterDTO} from '@/types/dto/auth'
import type {UserVO} from '@/types/vo/user'
import {TOKEN_KEY} from '@/constants/app'

interface AuthState {
    user: UserVO | null
    token: string | null
}

export const useAuthStore = defineStore('auth', {
    state: (): AuthState => ({
        user: null,
        token: localStorage.getItem(TOKEN_KEY),
    }),
    getters: {
        isLoggedIn: (state) => !!state.token,
    },
    actions: {
        async login(payload: UserLoginDTO) {
            const loginResult = await authApi.login(payload)
            this.token = loginResult.token
            this.user = loginResult.user
            localStorage.setItem(TOKEN_KEY, loginResult.token)
            return loginResult
        },
        async register(payload: UserRegisterDTO) {
            const loginResult = await authApi.register(payload)
            this.token = loginResult.token
            this.user = loginResult.user
            localStorage.setItem(TOKEN_KEY, loginResult.token)
            return loginResult
        },
        async fetchCurrentUser() {
            if (!this.token) return null
            try {
                // 导入 userApi
                const {userApi} = await import('@/api')
                const user = await userApi.getCurrentUser()
                this.user = user
                return user
            } catch (error) {
                // 如果获取用户信息失败，清除token
                this.logout()
                throw error
            }
        },
        async logout() {
            if (this.token) {
                try {
                    await authApi.logout()
                } catch (error) {
                    // 即使logout API失败，也要清除本地状态
                    console.warn('Logout API failed:', error)
                }
            }
            this.user = null
            this.token = null
            localStorage.removeItem(TOKEN_KEY)
        },
        // 初始化时检查token有效性
        async initAuth() {
            if (this.token) {
                try {
                    await this.fetchCurrentUser()
                } catch (error) {
                    console.warn('Token validation failed:', error)
                    this.logout()
                }
            }
        },
    },
})

